package com.yc;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 
 * @author yuancan
 * 参考链接：
 * https://www.jianshu.com/p/1b5e22167869
 * https://blog.csdn.net/qq_41223155/article/details/94985582
 */
//@Controller
@WebServlet(urlPatterns = "/demo1")
public class DemoServlet1 extends HttpServlet {
	
//	@Autowired
//	private DemoService1 demoService1;
	
    /**
     * Servlet和Spring框架整合时候, Servlet本身是不能自动依赖注入
     * 解决方案：
     * 1. Spring框架提供的接口, AutowireCapableBeanFactory
     * 2. 就可以完成Servlet中依赖对象的自动装配
     */
    @Override
    public void init() throws ServletException {
        /**
         * 利用init方法来调用Spring容器BeanFactory
         * 看看UserServlet是否能够通过Spring容器获取对象
         */
//        WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); //通过Web容器去得到BeanFactory对象
//        AutowireCapableBeanFactory autowireCapableBeanFactory = wc.getAutowireCapableBeanFactory();
//        autowireCapableBeanFactory.autowireBean(this);
    }

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("-----DemoServlet1-----doGet-");
		
		//获取容器对象
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        DemoService1 service = (DemoService1) context.getBean("demoService1");
        service.m1();
		
//		demoService1.m1();
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("-----DemoServlet1-----doPost-");
	}

	
	
}
